<script setup>
import { onMounted, ref } from "vue";
import luckysheet from "luckysheet";
import LuckyExcel from "luckyexcel";
import AnalyesAPI from "@/api/system/analyes.ts";
import { useAnalysetStore } from "@/store/index.ts";
import {
  filterValidSampleAdatas,
  filterValidSamples,
  processTableData,
  transformData,
  zkylSamples,
  splitDataIntoPages,
  getHeaders,
} from "@/utils/method";
// 复制粘贴
import Index from "@/components/analysisSheetComponents/component/index.vue";

import HzDevice from "@/components/analysisSheetComponents/component/HzDevice.vue";
import TpDevice from "@/components/analysisSheetComponents/component/TpDevice.vue";
import indexPdf from "@/components/analysisSheetComponents/ambientAir/tmpl78/indexPdf.vue";
var options = {
  container: "luckysheet", //luckysheet为容器id
  lang: "zh",
  autoCalculate: true,
  data: [
    {
      row: 9,
      celldata: [
        // 初始化表格数据，第一行包含表头
        { r: 0, c: 0, v: "样品唯一性标识" }, // A1
        { r: 1, c: 0, v: "样品编号" }, // B1
        { r: 1, c: 1, v: "滤筒编号" }, // B1
        { r: 0, c: 2, v: "标况体积V(m³)" }, // B1
        { r: 0, c: 3, v: "含氧ɸ'(O₂)(%)" }, // B1
        { r: 0, c: 4, v: "滤筒终重A(g)" }, // B1
        { r: 1, c: 4, v: "终重1	" }, // B1
        { r: 1, c: 5, v: "终重2" }, // B1
        { r: 1, c: 6, v: "终重3" }, // B1
        { r: 0, c: 7, v: "样品净重m(g)" }, // B1
        { r: 0, c: 8, v: "样品浓度C₁(mg/m³)" }, // B1
        { r: 0, c: 9, v: "监测浓度C(mg/m³)" }, // B1
        { r: 0, c: 10, v: "排放浓度C'(mg/m³)" }, // B1
        { r: 0, c: 11, v: "备注" }, // B1
      ], // 初始化数据
      config: {
        merge: {
          "0_0": {
            r: 0, // 起始行
            c: 0, // 起始列
            rs: 1, // 跨越的行数
            cs: 2, // 跨越的列数
          },
          "0_2": {
            r: 0, // 起始行
            c: 2, // 起始列
            rs: 2, // 跨越的行数
            cs: 1, // 跨越的列数
          },
          "0_3": {
            r: 0, // 起始行
            c: 3, // 起始列
            rs: 2, // 跨越的行数
            cs: 1, // 跨越的列数
          },
          "0_4": {
            r: 0, // 起始行
            c: 4, // 起始列
            rs: 1, // 跨越的行数
            cs: 3, // 跨越的列数
          },
          "0_7": {
            r: 0, // 起始行
            c: 7, // 起始列
            rs: 2, // 跨越的行数
            cs: 1, // 跨越的列数
          },
          "0_8": {
            r: 0, // 起始行
            c: 8, // 起始列
            rs: 2, // 跨越的行数
            cs: 1, // 跨越的列数
          },
          "0_9": {
            r: 0, // 起始行
            c: 9, // 起始列
            rs: 2, // 跨越的行数
            cs: 1, // 跨越的列数
          },
          "0_10": {
            r: 0, // 起始行
            c: 10, // 起始列
            rs: 2, // 跨越的行数
            cs: 1, // 跨越的列数
          },
          "0_11": {
            r: 0, // 起始行
            c: 11, // 起始列
            rs: 2, // 跨越的行数
            cs: 1, // 跨越的列数
          },
        }, // 合并单元格
        columnlen: {
          // 设置列宽
          0: 130, // 第一列宽度 150px
          1: 130, // 第二列宽度 120px
          2: 130, // 第三列宽度 180px
          3: 130, // 第四列宽度 100px
          4: 130, // 第五列宽度 200px
          5: 130, // 第六列宽度 150px
          6: 130, // 第六列宽度 150px
          7: 130, // 第六列宽度 150px
          8: 130, // 第六列宽度 150px
          9: 130, // 第六列宽度 150px
          10: 130, // 第六列宽度 150px
          11: 130, // 第六列宽度 150px
          12: 130, // 第六列宽度 150px
        }, // 表格列宽
      },
    },
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};
const tableOption = ref([{ table: "仪器名称", id: 1 }]);
const processedData = ref([]);
const ypbhOptions = ref([]);
const cdatas = ref([]);
const analyseStatusPage = useAnalysetStore();
const record_sn = analyseStatusPage.waterForm.record_sn;
const switchAdd = ref(true);
const checkTime = ref("");
const waterForm = ref({
  device: {
    device_name: [],
    device_model: [],
    device_number: [],
    tp_device_name: [],
    tp_device_model: [],
    tp_device_number: [],
  },
});
// pdf显示隐藏
const showTargetPage = ref(false);
const tableHeaders = ref([]);
const tabler = ref([]);
const sheetData = ref("");
// 在组件挂载后初始化 Lucky-sheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  // 获取初始数据并保存在响应式变量中
  sheetData.value = options.data;
  // 获取表单信息
  getWaterCapacity();
  // 复制粘贴
  getMethod();
});

// 获取信息( 复制粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number; //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
    ? analyseStatusPage.waterForm.tableItem.test_method
    : analyseStatusPage.waterForm.tableItem.test_method_number; //分析方法
  waterForm.value.category_id =
    analyseStatusPage.waterForm.tableItem.sample_category; // 样品类别
  checkTime.value = analyseStatusPage.waterForm.tableItemList.submit_dates;
};
// 获取工作表信息
const getWaterCapacity = () => {
  let json = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 25,
    record_sn: record_sn,
    // record_sn: 40,
  };
  AnalyesAPI.getAnalyseACapacity(json).then((data) => {
    console.log("获取水质容量 A单", data);
    // 复制粘贴
    if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data;
      sheetData.value = data.configs;
      options.data = sheetData.value;
      luckysheet.create(options);
      processedData.value = data.adatas;
      //处理adata到pdf
      tableHeaders.value = splitDataIntoPages(data.adatas, 18);
      tabler.value = getHeaders(data.adatas, 23);
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
        tp_device_name: [],
        tp_device_model: [],
        tp_device_number: [],
      };
    }
  });
};
// 保存新增表单
const handleAddWaterPh = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map((row) => {
    return row
      .map((cell) => {
        return cell
          ? {
              field: cell.m || "默认字段",
              value: cell.v || null,
            }
          : null;
      })
      .filter((cell) => cell !== null); // 删除 null 值
  });
  // processedData.value = filterValidSampleAdatas(processTableData(data));
  processedData.value = processData(data);
  cdatas.value = filterValidSamples(transformData(processedData.value));
  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status;
    delete waterForm.value.reviewer_id;
  }
  //   调保存新增接口
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    record_sn: record_sn,
    // record_sn: 41,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value,
  }).then((data) => {
    ElMessage.success("保存成功！");
    switchAdd.value = false;
  });
};

const processData = (data) => {
  if (!data || data.length < 2) {
    return [];
  }
  // 提取表头信息
  const header1 = data[0]
    .map((item) => item.value)
    .filter((value) => value !== null);

  const header2 = data[1]
    .map((item) => item.value)
    .filter((value) => value !== null);

  // const row = data[2].map(item => item.value);
  const row = data.slice(2).map((rowData) => rowData.map((item) => item.value));
  const resultArray = [];
  for (let i = 0; i < row.length; i++) {
    const currentRow = row[i];
    const result = {
      [header2[0]]: currentRow[0] || null, // 样品编号
      [header2[1]]: currentRow[1] || null, // 滤筒编号
      [header1[1]]: currentRow[2] || null, // 标况体积
      [header1[2]]: currentRow[3] || null, // 含氧
      [header2[2]]: currentRow[4] || null, // 终重1
      [header2[3]]: currentRow[5] || null, // 终重2
      [header2[4]]: currentRow[6] || null, // 终重3
      [header1[4]]: currentRow[7] || null, // 样品净重,
      [header1[5]]: currentRow[8] || null, // 样品浓度,
      [header1[6]]: currentRow[9] || null, // 检测浓度
      [header1[7]]: currentRow[10] || null, // 排放浓度
      [header1[8]]: currentRow[11] || null, // 备注
    };

    resultArray.push(result);
  }
  console.log(resultArray, "resultArray");
  return resultArray;
};

function formatLuckysheetData(sheetData) {
  const formattedData = [];

  // 假设第一行为标题行
  const headers = sheetData[0].cells.map((cell) => cell.v);

  // 遍历每一行数据（从第二行开始）
  for (let i = 1; i < sheetData.length; i++) {
    const row = sheetData[i];
    const rowData = {};

    // 将每行的数据映射到对象属性
    row.cells.forEach((cell, index) => {
      rowData[headers[index]] = cell.v;
    });

    formattedData.push(rowData);
  }

  return formattedData;
}

// 用于获取最新的表格数据
const getUpdatedData = () => {
  if (jsonData.value === null) {
    sheetData.value = luckysheet.getLuckysheetfile();
  } else {
    sheetData.value = jsonData.value.sheets[0];
  }
  // const data = formatLuckysheetData(sheetData.value)
  // console.log(data)
  const tableDataString = JSON.stringify(sheetData.value); // 将表格数据转为 JSON 字符串
  localStorage.setItem("tableData", tableDataString);
  console.log(sheetData.value); // 打印当前表格的数据
};

// 上传文件
const loadExcel = (evt) => {
  const files = evt.target.files;
  console.log(files);
  if (files == null || files.length == 0) {
    alert("No files wait for import");
    return;
  }
  let name = files[0].name;
  let suffixArr = name.split("."),
    suffix = suffixArr[suffixArr.length - 1];
  if (suffix != "xlsx") {
    alert("Currently only supports the import of xlsx files");
    return;
  }
  LuckyExcel.transformExcelToLucky(
    files[0],
    function (exportJson, luckysheetfile) {
      if (exportJson.sheets == null || exportJson.sheets.length == 0) {
        alert(
          "Failed to read the content of the excel file, currently does not support xls files!"
        );
        return;
      }
      console.log("exportJson", exportJson.sheets);
      jsonData.value = exportJson;

      luckysheet.destroy();
      luckysheet.create({
        container: "luckysheet", //luckysheet is the container id
        showinfobar: false,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator,
      });
    }
  );
};

const handleSwitch = () => {
  switchAB.value = !switchAB.value;
};

// 下载
const downloadDetail = async () => {
  console.log("下载");
  showTargetPage.value = true;
  await nextTick();
  window.print();
  setTimeout(() => {
    showTargetPage.value = false;
  }, 1000);
};
</script>

<template>
  <div class="card">
    <div v-show="!showTargetPage">
      <el-card class="box-card">
        <h1 style="text-align: center">固定污染源废气 颗粒物分析原始记录</h1>
        <div>SXLPHJ/JL/CX-22-78</div>
        <table class="table">
          <tr>
            <td colspan="3">任务编号</td>
            <td colspan="3">
              <el-input
                v-model="waterForm.task_name"
                style="width: 100px; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2">采样日期</td>
            <td colspan="1">
              <el-input
                v-model="waterForm.sampling_time"
                style="width: 100px; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2">分析日期</td>
            <td colspan="1">
              <el-input
                v-model="waterForm.anal_time"
                style="width: 100px; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="3" style="width: 50%">环境温度</td>
            <td colspan="2">
              <el-input
                v-model="waterForm.temperature"
                style="width: 100px; border: 1px solid transparent"
                placeholder="请输入"
              />
              ℃
            </td>
            <td colspan="1" style="width: 20%">环境湿度</td>
            <td colspan="1">
              <el-input
                v-model="waterForm.humidity"
                style="width: 80px; border: 1px solid transparent"
                placeholder="请输入"
              />
              %RH
            </td>
          </tr>
          <tr>
            <td>分析方法</td>
            <td colspan="14">
              <el-input
                v-model="waterForm.method"
                style="width: 160px; border: 1px solid transparent"
                placeholder="请输入"
              />
              %
            </td>
            <td colspan="2">基准含氧量ɸ(O₂)</td>
            <td colspan="3">
              <el-input
                v-model="waterForm.jzyhl"
                style="width: 160px; border: 1px solid transparent"
                placeholder="请输入"
              />
              %
            </td>
          </tr>
          <tr>
            <!-- <td colspan="13">
              恒重仪器：
              <el-input style="width: 120px; border: 1px solid transparent" />
              仪器型号：
              <el-input style="width: 120px; border: 1px solid transparent" />
              仪器编号：
              <el-input style="width: 120px; border: 1px solid transparent" />
            </td> -->
            <HzDevice :water-form="waterForm" />
            <td colspan="1" rowspan="2">计算公式</td>
            <td colspan="5" rowspan="2">
              <el-input
                v-model="waterForm.js_formula"
                style="width: 450px; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <tr>
            <TpDevice :water-form="waterForm" />
            <!-- <td colspan="12">
              天平级别：
              <el-input style="width: 120px; border: 1px solid transparent" />
              天平型号：
              <el-input style="width: 120px; border: 1px solid transparent" />
              天平编号：
              <el-input style="width: 120px; border: 1px solid transparent" />
            </td> -->
          </tr>
          <tr>
            <td colspan="3">标准滤筒编号</td>
            <td colspan="2">原始质量(g)</td>
            <td colspan="2">采样日期</td>
            <td colspan="1">称重1(g)</td>
            <td colspan="2">称重2(g)</td>
            <td colspan="1">称重3(g)</td>
            <td colspan="3">环境温度</td>
            <td colspan="2">与原始质量差值(g)</td>
            <td colspan="2">允许差值(g)</td>
            <td colspan="3">是否合格</td>
          </tr>
          <tr v-for="rowIndex in 2" :key="rowIndex">
            <td colspan="3" />
            <td colspan="2" />
            <td colspan="2" />
            <td colspan="1" />
            <td colspan="2" />
            <td colspan="1" />
            <td colspan="3" />
            <td colspan="2" />
            <td colspan="2" />
            <td colspan="3" />
          </tr>
          <tr>
            <td colspan="2">备注</td>
            <td colspan="21">
              <el-input
                v-model="waterForm.notes"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
        </table>

        <!--      <input id="uploadBtn" type="file" @change="loadExcel"/>-->
        <div id="luckysheet" style="width: 100%; height: 500px" />
      </el-card>
    </div>

    <div v-show="showTargetPage">
      <indexPdf
        :waterForm="waterForm"
        :tableHeaders="tableHeaders"
        :tabler="tabler"
      />
    </div>

    <!--    底部公共按钮 (复制粘贴)-->
    <div v-show="!showTargetPage">
      <Index
        :water-form="waterForm"
        :handle-add-water-ph="handleAddWaterPh"
        :download-detail="downloadDetail"
        :check-time="checkTime"
        :get-water-capacity="getWaterCapacity"
        :switch-add="switchAdd"
      />
    </div>
  </div>
</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  /* 表格边框合并 */
  text-align: left;
  /* 默认左对齐 */
  font-size: 14px;
  /* 字体大小 */
  color: #606266;
  /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf;
  /* 表格单元格边框颜色 */
  padding: 12px;
  /* 单元格内边距 */
}

.table th {
  background: #f5f7fa;
  /* 表头背景色 */
  font-weight: 600;
  /* 表头字体加粗 */
  color: #303133;
  /* 表头字体颜色 */
  text-align: center;
  /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
